package com.wframe.project.former.task;

import com.frame.database.JdataBean;
import com.wframe.project.jnd.extinterface.sms.SmsUtil;
import com.wframe.project.jnd.services.PurchaseTempService;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.Timestamp;
import java.util.*;

/**
 * Created by lwb on 2017/5/12.
 */
public class PurchaseRemindTask {

    @Autowired
    PurchaseTempService tempService;

    @RedisLock("purchaseRemindTask")
    public void exectask() {
        List<JdataBean> plan = tempService.findPlan();

        int size = plan.size();
        if (size > 0) {
            while (true) {
                if (size == 0) {
                    break;
                }

                for (int i = 0; i < size; i++) {
                    JdataBean bean = plan.get(i);
                    long remindTimeMillis = Timestamp.valueOf(bean.getString("reminddata")).getTime();
                    long currentTimeMillis = System.currentTimeMillis();
                    if (Math.abs(remindTimeMillis - currentTimeMillis) < 5 * 60 * 1000) {
                        //发送短信
                        new SmsUtil().sendPurchaseRemind(bean.getString("remindphone"), bean.getString("loginname"), bean.getString("name"), bean.getString("remindcon"));
                        //删除已发送计划
                        plan.remove(i);
                        size--;
                        if (bean.getInt("remindrepeat") == 1) {
                            //变更下次提醒时间
                            Calendar ca = Calendar.getInstance();
                            ca.setTimeInMillis(remindTimeMillis);
                            ca.add(Calendar.DATE, bean.getInt("repeatday"));
                            Map columnMap = new HashMap();
                            columnMap.put("reminddata", ca.getTime());
                            tempService.updateById(columnMap, bean.get("id"));
                        }
                    }
                }
            }
        }
    }

}
